const app = getApp();

Page({
  data: {
    portrait: '/pages/img/user_img.png',
    mobile: "",
    name: "",
    num: 0,
    vol: 0,
    count: 0,
    weight: "0",
    hide: "",
    type: "",
    carup: "display:none;",
    ware: "display:none;",
    distance: 0, // 手指移动的距离
    scale: 1, // 缩放比例
    baseWidth: '', // 图片实际宽度
    baseHeight: '', // 图片实际高度
    initWidth: '', // 图片默认显示宽度
    initHeight: '', // 图片默认显示高度
    scaleWidth: '', // 图片缩放后的宽度
    scaleHeight: '', // 图片缩放后的高度
  },

  /**
   * 监听图片加载成功时触发
   */
  imgload: function (e) {
    this.multiple = e.detail.width / this.width; // 计算原图和默认显示的倍数
    let height = this.multiple > 1 ? e.detail.height / this.multiple : e.detail.height; // 等比例计算出默认高度
    let width = this.multiple > 1 ? this.width : e.detail.width;
    this.setData({
      baseWidth: e.detail.width, // 获取图片实际宽度
      baseHeight: e.detail.height, // 获取图片实际高度
      initWidth: width,
      initHeight: height,
      scaleWidth: width,
      scaleHeight: height,
    });
  },

  /**
   * 双手指触发开始 计算开始触发两个手指坐标的距离
   */
  touchstartCallback: function (e) {
    // 单手指缩放开始，不做任何处理
    if (e.touches.length == 1) return;
    let distance = this.calcDistance(e.touches[0], e.touches[1]);
    this.setData({
      'distance': distance,
    });
  },

  /**
   * 双手指移动   计算两个手指坐标和距离
   */
  touchmoveCallback: function (e) {
    // 单手指缩放不做任何操作
    if (e.touches.length == 1) return;
    let distance = this.calcDistance(e.touches[0], e.touches[1]);
    // 计算移动的过程中实际移动了多少的距离
    let distanceDiff = distance - this.data.distance;
    let newScale = this.data.scale + 0.005 * distanceDiff;

    if (newScale >= this.multiple && this.multiple > 2) { // 原图比较大情况
      newScale = this.multiple;
    } else if (this.multiple < 2 && newScale >= 2) { // 原图较小情况
      newScale = 2; // 最大2倍
    };
    // 最小缩放到0.3
    if (newScale <= 0.3) {
      newScale = 0.3;
    };

    let scaleWidth = newScale * this.data.initWidth;
    let scaleHeight = newScale * this.data.initHeight;
    this.setData({
      distance: distance,
      scale: newScale,
      scaleWidth: scaleWidth,
      scaleHeight: scaleHeight,
      diff: distanceDiff
    });
  },

  /**
   * 计算两个手指距离
   */
  calcDistance(pos0, pos1) {
    let xMove = pos1.clientX - pos0.clientX;
    let yMove = pos1.clientY - pos0.clientY;
    return Math.sqrt(xMove * xMove + yMove * yMove);
  },

  onLoad: function (options) {
    // 获取屏幕宽度
    this.width = wx.getSystemInfoSync().windowWidth;
    wx.setNavigationBarTitle({
      title: '我的'
    });

    this.updateUserInfo();
  },
  onShow: function (options) {
    this.getTabBar().setData({
      current: 'setting'
    })
  },

  // 检测下拉刷新事件
  onPullDownRefresh: function () {
    this.init();
    wx.stopPullDownRefresh();
  },

  login: function () {
    this.loginUser();
  },

  carApply: function () {
    wx.navigateTo({
      url: "/pages/car_apply/car_apply"
    });
  },

  setting: function () {
    if (!this.isLogin()) {
      wx.showToast({
        title: "请先登录系统才能进行个人资料的查询!",
        icon: 'none', // 如果要纯文本，不要icon，将值设为'none'
        duration: 2000
      });
      return;
    }
    this.updateData();
  },

  uploadCar: function () {
    wx.navigateTo({
      url: "/pages/upload_car/upload_car"
    });
  },

  reLogin: function () {
    wx.showModal({
      title: '重新登录',
      content: "重新登录会刷新您的身份信息,确认要重新登录么?",
      success: (res) => {
        if (res.confirm) {
          this.loginUser();
        }
      }
    });
  },

  historyOrders: function () {
    if (!this.isLogin()) {
      wx.showToast({
        title: "请先登录系统才能进行历史订单的查询!",
        icon: 'none', // 如果要纯文本，不要icon，将值设为'none'
        duration: 2000
      });
      return;
    }
    if (!this.isUserType()) {
      wx.showToast({
        title: "请先选择您的身份,进入我的页面点击点击个人资料选择身份才可接单!",
        icon: 'none', // 如果要纯文本，不要icon，将值设为'none'
        duration: 2000
      });
      return;
    }
  },

  // 查询当前资质
  aptitude: function () {
    wx.request({
      url: app.serverIP + '/kkl/cms/app/Users/' + getApp().id + '?token=' + app.token,
      dataType: "json",
      success: (res) => {
        if (res.data.code == "200") {
          let tipStr = "";
          if (res.data.data.driverState == 1) {
            tipStr = "正在等待工作人员审核您的信息";
          } else if (res.data.data.driverState == 2) {
            tipStr = "您已通过审核";
          } else if (res.data.data.driverState == 3) {
            tipStr = "您的申请被驳回请根据提示重新上传附件并修改个人资料\r\n" + res.data.data.remarks + "\r\n";
          }
          wx.showModal({
            title: '资质信息',
            content: tipStr,
            success: () => {}
          });
        }
      },
    });
  },

  // 平面图预览
  openGallery: function () {
    this.setData({
      istrue: true
    });
  },

  // 关闭平面图预览
  closeGallery: function () {
    this.setData({
      istrue: false
    });
  },

  /**
   * 更新用户信息
   */
  updateUserInfo: function () {
    if (this.isLogin()) {
      this.setData({
        mobile: app.userInfo.mobile,
        name: app.userInfo.name,
        hide: "display:none;",
        type: this.getIdentity(app.userInfo.userType, app.userInfo.carrierName)
      });
      console.log(app.userInfo);
    } else {
      this.setData({
        hide: ""
      });
    }
  },

  /**
   * 判断是否登录
   */
  isLogin: function () {
    return app.userInfo != null;
  },

  /**
   * 判断用户类型
   */
  isUserType: function () {
    return app.userInfo.userType != null && app.userInfo.userType !== "";
  },

  /**
   * 登录用户
   */
  loginUser: function () {
    wx.login({
      success: (res) => {
        if (res.code) {
          wx.showToast({ // 显示加载中loading效果2秒
            title: '正在登录',
            icon: 'loading',
            duration: 5000 // 提示的延迟时间
          });
          wx.request({
            url: app.serverIP + 'kkl/cms/app/login?code=' + res.code, // 请求地址
            method: "POST",
            success: (res) => {
              wx.showToast({
                title: res.data.message,
                icon: 'none', // 如果要纯文本，不要icon，将值设为'none'
                duration: 2000
              });
              console.log(res.data.message);
              getApp().userInfo = res.data.data;
              getApp().token = res.data.data.token;
              getApp().id = res.data.data.id;
              getApp().openId = res.data.data.openId;
              getApp().companyId = res.data.data.companyId;

              if (res.data.data.driverName == null || res.data.data.driverName == "") {
                this.setData({
                  mobile: "　",
                  name: "　",
                  hide: "display:none;"
                });
                getApp().userInfo.name = "　";
                this.updateData();
              } else {
                this.setData({
                  mobile: app.userInfo.driverMobile,
                  name: app.userInfo.driverName,
                  hide: "display:none;",
                  type: this.getIdentity(app.userInfo.userType, app.userInfo.carrierName)
                });
              }
            },
          });
        } else {
          console.log('登录失败！' + res.errMsg);
        }
      }
    });
  },

  /**
   * 更新数据
   */
  updateData: function () {
    wx.navigateTo({
      url: "/pages/update_data/update_data"
    });
  },

  /**
   * 初始化页面数据
   */
  init: function () {
    this.updateUserInfo();
  },

  /**
   * 获取用户身份
   */
  getIdentity: function (userType, carrierName) {
    let type = "";
    if (userType == 1) {
      this.setData({
        carup: ""
      });
      type = "司机 (" + carrierName + ")";
    } else if (userType == 2) {
      type = "承运商 (" + carrierName + ")";
    } else if (userType == 3) {
      type = "调度";
    } else if (userType == 4) {
      this.setData({
        ware: ""
      });
      type = "保管";
    }
    return type;
  }
});